import { getQueryValue, isArray, objHas } from '@/utils/util.js';

/*
 * url传参需要需要做如下处理
 * 对象示例：
 * events = {
 *   test: {                // 事件名
 *     category: '吉利莲'    // 参数
 *   },
 *   test1: {
 *     name: 'aaa',
 *     code: '100'
 *   }
 * }
 * 网址传参: `&vsEvt=${window.encodeURIComponent(JSON.stringify(events))}`
 */

const formatEvent = (evt, index) => evt;

// 获取url传参的所有事件对象
export const getAllUrlEvents = () => {
  const vsEvtStr = getQueryValue('vsEvt');
  if (vsEvtStr === null) {
    return {};
  }
  const json = window.decodeURIComponent(vsEvtStr, true);
  const events = JSON.parse(json);
  return events;
};

// 获取跟组件匹配的事件对象
export const getMatchUrlEvents = vmEvents => {
  const evtKeys = [];
  vmEvents.forEach(n => {
    if (n.type === 'in' && n.key) {
      evtKeys.push(n.key);
    }
  });
  if (!evtKeys.length) {
    return {};
  }

  const allEvents = getAllUrlEvents();
  const matchEvents = {};
  evtKeys.forEach(evtKey => {
    if (objHas(allEvents, evtKey)) {
      matchEvents[evtKey] = allEvents[evtKey];
    }
  });
  return matchEvents;
};

// 添加url事件参数到params
export const addUrlParamsBySourceType = (dataSourceType, params, matchEvents) => {
  let _params = params;

  let parameters = {};

  Object.entries(matchEvents).map(([evtKey, _parameters]) => {
    parameters = {
      ...parameters,
      ..._parameters,
    };
  });

  if (['xMiner', 'xMinerPublicDatabase', 'fabric', 'Dac'].includes(dataSourceType)) {
    if (!params) {
      _params = [];
    }

    Object.entries(parameters).map(([key, val]) => {
      _params.push({
        code: key,
        value: val,
        sendTime: 0, // 保证在最前面
      });
    });
    return _params;
  } else if (dataSourceType === 'xTag') {
    let { conditions = [], sqlParams = [] } = params;
    const item = {
      terms: [],
    };
    const { terms } = item;

    Object.entries(parameters).map(([key, val]) => {
      // conditions 部分
      terms.push({
        [key]: [val],
      });
      conditions.push(item);
      params.conditions = conditions;

      // sqlParams 部分
      sqlParams.push({
        key,
        value: val,
      });
    });
    if (!conditions.length) {
      conditions = [{}];
    }
    params.conditions = conditions;
  } else {}
  return null;
};

// 格式化接收到的事件
export const formatEvents = matchEvents => {
  const events = [];
  Object.entries(matchEvents).map(([eventKey, parameters]) => {
    const evtItem = {
      eventKey,
      parameters,
      sendTime: 1, // 排在公用事件后面
    };
    events.push(evtItem);
  });
  return events;
};
